import 'package:HnXG/Api.dart';
import 'package:HnXG/DIalog.dart';
import 'package:HnXG/Request/Request4.dart';
import 'package:HnXG/snackbar.dart';
import 'package:flutter/material.dart';

class TaskViewPage extends StatefulWidget {

  const TaskViewPage({super.key});
  
  @override
  State<StatefulWidget> createState() => _TaskViewPage();
  }

 

class _TaskViewPage extends State<TaskViewPage> {
  Future<Map<String, dynamic>>? _taskData;  // 新增数据请求变量

  @override
  void initState() {
    super.initState();
    _taskData = Api.GetView_TaskOrder();  // 初始化时获取数据
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.blue, // 新增背景色
        title: const Text('任务列表',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            shadows: [Shadow(color: Colors.black38, offset: Offset(1,1), blurRadius: 3)],
          )
        ),
        centerTitle: true, // 新增标题居中
        elevation: 3, // 新增阴影效果
      ),
      body: FutureBuilder(
        future: _taskData,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('错误: ${snapshot.error}'));
          }
          
          // 添加空值检查
          final responseData = snapshot.data;
          if (responseData == null) {
            return const Center(child: Text('无返回数据'));
          }

          // 添加布尔值类型转换保护
          if (responseData.containsKey('error')) {
            return Center(child: Text('接口错误: ${responseData['message']}'));
          }

          final dataList = (responseData['dto'] as List?) ?? [];
     
          if (dataList.isEmpty) {
            return const Center(child: Text('暂无任务'));
          }

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              final item = dataList[index];
              return Card(
                child: ListTile(
                  title: Text('任务单号: ${item['taskOrderCode']}'),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('创建时间: ${_formatDate(item['createTime'])}'),
                      // 添加布尔值转换保护
                      Text('发送状态: ${(item['isSend'] ?? false) ? '已发送' : '未发送'}'),
                      Text('起始位置: ${item['origination_PositionCode']}'),
                      Text('目标位置: ${item['target_PositionCode']}'),
                       Text('队列id: ${item['info']}'),
                      ElevatedButton(
                        onPressed: () async {
                          // 这里可以添加处理任务单号的逻辑
                          final taskOrderCode = item['taskOrderCode'];
                              final result = await InfoDialog.show(context, "提示信息", "您确定要取消任务吗？");
                if (result == true) {

                    var response= await Api.CancelTaskOrder(Request4(TaskOrderCode: taskOrderCode ) );
                        if(response["state"]==true){
                             setState(() {
                               _taskData = Api.GetView_TaskOrder();
                             });
                             SuccessSnackBar.show(context, message: response["msg"]);
                           }
                           else{
                            ErrorSnackBar.show(context, message: response["msg"]);
                           }
                }
                         
                       
                        },
                        child: const Text('取消任务,释放目标库位'),
                      ),
                    ],
                  ),
                  dense: true,
                ),
              );
            },
          );
        },
      ),
    );
  }

  String _formatDate(dynamic timestamp) {
    // 添加更严格的空值检查
    if (timestamp == null || timestamp.toString().isEmpty) return '未知时间';
    try {
      final date = DateTime.parse(timestamp.toString());
      return '${date.year}-${date.month.toString().padLeft(2,'0')}-${date.day.toString().padLeft(2,'0')} '
             '${date.hour.toString().padLeft(2,'0')}:${date.minute.toString().padLeft(2,'0')}';
    } catch (e) {
      return '无效时间';
    }
  }
}